<script lang="ts" setup>
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue'

// do not use same name with ref
const form = reactive({
  ID: '',
  name: '',
  password: '',
  email: '',
  count: ''
})

const loading = ref(false)  //用于控制按钮加载状态

const onSubmit = async () => {
  if(!form.ID && !form.name && !form.password){
    console.error('读者ID、读者姓名和读者密码不能为空')
    return
  }
  try {
    loading.value = true // 提交前开始加载
    const response = await request.post('/useradd', {
      id: form.ID,
      name: form.name,
      password:form.password,
      email:form.email,
      count:form.count
    })

    if (response.status === 200 && response.data.status === 'success') {
      console.log('添加读者成功', response.data)
    } 
      ElMessage.success('添加读者成功')
  } catch (error) {
    console.error('Failed to add category:', error)
    ElMessage.error('服务器发生错误，请稍后重试')
  } finally {
    loading.value = false // 请求结束后关闭加载
  }
}
</script>

<template>
    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <el-form-item label="编号">
        <el-input v-model="form.ID" placeholder="请输入读者编号" />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.name" placeholder="请输入读者姓名"/>
      </el-form-item>
      <el-form-item label="密码">
        <el-input 
            v-model="form.password" 
            placeholder="请输入密码"
            show-password
            type="password"
        />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email" placeholder="请输入读者邮箱"/>
      </el-form-item>
      <el-form-item label="可借数量">
        <el-input v-model="form.count" placeholder="请输入读者可借图书的数量" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
</template>
  

<style lang="scss" scoped>

</style>